//
//  BRMerchantVC.m
//  Kexu
//
//  Created by IOS on 2023/7/31.
//

#import "BRMerchantVC.h"
#import "BRWithdrawalVC.h"
#import "BRWRentalOrderVC.h"
#import "BRWTRecordVC.h"
#import "BRWithdrawalRecordVC.h"
#import "BRMyDeviceVC.h"
#import "BRMerchantModel.h"
#import "BRMShopInfoViewController.h"

#import "BRShopSelView.h"

@interface BRMerchantVC ()
{
    UIStackView *_funcSstack;
    QMUIButton *_withrawalBtn;
    QMUIButton *_wRecordBtn;
}
@property (nonatomic,strong) UIStackView *stackTitle;

@property (nonatomic,strong) BRMData2StackView *topStack;

@property (nonatomic,strong) QMUILabel *balanL;

@property (nonatomic,strong) BRMerchantModel *dto;

@property (nonatomic,strong) BRShopSelView *shopListView;

@property (nonatomic,strong) BRMoreBtn *shopListBtn;

@property (nonatomic,strong) UIScrollView *sView;

@end

@implementation BRMerchantVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUI];
    
    [self requestData];
}

#pragma mark - net --
- (void)requestData {
    
    
    [[BRRequestManager shared] GET:[BRAPI merchant] params:@{@"branchId":USERManager.branchId} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        self.dto = [BRMerchantModel mj_objectWithKeyValues:dataDict[@"data"]];
        
        
        self.balanL.text = [BRPayManager br_amount:self.dto.pendingAmount];
        
        [self.topStack br_text:[BRPayManager br_amount:self.dto.profitToday] by:0];
        [self.topStack br_text:[NSString stringWithFormat:@"%ld",self.dto.todayTotalOrder] by:1];
        
        [self br_text:[BRPayManager br_amount:self.dto.profitTotal] by:0];
        [self br_text:[NSString stringWithFormat:@"%ld",self.dto.totalOrder] by:1];
        [self br_text:[BRPayManager br_amount:self.dto.settledAmount] by:2];
        [self handleEndRefreshForView:self.sView];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [self handleEndRefreshForView:self.sView];
        // 没有权限
        if (code == 21334) {
            WS(weakSelf);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf pop];
            });
        }
    }];
    
}

- (void)handleListRefreshAction {
    
    [self requestData];
}

#pragma mark - func --
- (void)toMenuTag:(UIControl *)btn {
    
    NSInteger index = btn.tag - 500;
    
    if (index == 0) {
        BRWRentalOrderVC *vc = [[BRWRentalOrderVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
        
    }
    if (index == 1) {
        BRWTRecordVC *vc = [[BRWTRecordVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
        
    }
    if (index == 2) {
        BRMyDeviceVC *vc = [[BRMyDeviceVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
        
    }
    
    if (index == 3) {
        [self toInfo];
        return;
    }
}

- (void)toWithdrawal {
    
    BRWithdrawalVC *vc = [[BRWithdrawalVC alloc] init];
    vc.withdrawalAmount = self.dto.pendingAmount;
    [self.navigationController pushViewController:vc animated:YES];
    WS(weakSelf);
    vc.succBlock = ^{
        [weakSelf requestData];
    };
}


- (void)br_text:(NSString *)text by:(NSInteger)index {
    BRODListView *cell = [self.stackTitle viewWithTag:2000 + index];
    cell.textL.text = text;
}

- (void)toInfo {
    BRMShopInfoViewController *vc = [[BRMShopInfoViewController alloc] init];
    vc.branchId = USERManager.branchId;
    [self.navigationController pushViewController:vc animated:YES];
    WS(weakSelf);
    vc.editSuccBlock = ^(NSString *shopName) {
        [weakSelf resetName:shopName];
    };
}

- (void)resetName:(NSString *)name {
    
    self.shopListBtn.titleL.text = name;
    [self.shopListView resetName:name shopId:USERManager.branchId];
}


- (void)toWRecord {
    BRWithdrawalRecordVC *vc = [[BRWithdrawalRecordVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

/// 切换商家
- (void)changeMerchant:(UITapGestureRecognizer *)btn {
    
    // 获取点击的视图
    UIView *tappedView = btn.view;
    
    // 将视图坐标转换到 window 的坐标系
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    CGRect rectInWindow = [tappedView convertRect:tappedView.bounds toView:window];
    
    CGPoint new = CGPointMake(rectInWindow.origin.x, rectInWindow.origin.y + 42);
    
    [self.shopListView br_show:new];
}

- (void)hiddenSetting {
    BOOL hasSet = USERManager.branchId.length != 0;
    BRImgListView *setCell = [_funcSstack viewWithTag:603];
    setCell.hidden = !hasSet;
    BRImgListView *cell = (BRImgListView *)[_funcSstack viewWithTag:602];
    cell.line.hidden = !hasSet;
    
    _withrawalBtn.hidden = setCell.hidden;
    _wRecordBtn.hidden = setCell.hidden;
}

#pragma mark - UI --
- (void)setUI {
    
    self.view.backgroundColor = kColorBGF5;
    
    BRNavView *top = [self br_createTop:Localized(@"shop_merchantCenter")];
    CGFloat content_y = 190 + kSafeAreaTopHeight + 8;
    top.mj_h = content_y;
    
    UIScrollView *sView = [[UIScrollView alloc] init];
    sView.backgroundColor = UIColor.clearColor;
    [self.view addSubview:sView];
    [sView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(kSafeAreaTopHeight);
        make.left.right.bottom.offset(0);
    }];
    _sView = sView;
    [self addRefreshActionForView:sView];
    
    UIView *contView = [[UIView alloc] init];
    contView.backgroundColor = UIColor.clearColor;
    [sView addSubview:contView];
    [contView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth);
        make.edges.offset(0);
    }];
    
    //-------商户选择------
    BRMoreBtn *shopListBtn = [[BRMoreBtn alloc] init];
    shopListBtn.cornerRadius  = 18;
    [contView addSubview:shopListBtn];
    [shopListBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.offset(16);
        make.height.mas_equalTo(36);
        make.width.mas_equalTo(kScreenWidth / 2.0 - 22);
    }];
    UITapGestureRecognizer *moreBtn = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeMerchant:)];
    [shopListBtn addGestureRecognizer:moreBtn];
    self.shopListBtn = shopListBtn;
    shopListBtn.titleL.text = Localized(@"shop_totalMerchant");
    //-------------
    BRMData2StackView *topStack = [[BRMData2StackView alloc] initWhit:@[Localized(@"shop_todayProfit"),Localized(@"shop_todayOrder")]];
    [contView addSubview:topStack];
    [topStack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.height.mas_equalTo(70);
        make.top.equalTo(shopListBtn.mas_bottom).offset(16);
    }];
    _topStack = topStack;
    //---------balanceBG
    UIView *balanceBG = [[UIView alloc] init];
    balanceBG.backgroundColor = kUIColorMainTint;
    balanceBG.layer.cornerRadius = 10;
    balanceBG.layer.masksToBounds = YES;
    [contView addSubview:balanceBG];
    [balanceBG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.top.equalTo(topStack.mas_bottom).offset(10);
    }];
    
    QMUIButton *withrawalBtn = [[QMUIButton alloc] init];
    [withrawalBtn setBackgroundColor:kColorMain];
    withrawalBtn.layer.cornerRadius = 8;
    withrawalBtn.layer.masksToBounds = YES;
    [withrawalBtn setTitle:Localized(@"shop_withdrawal") forState:UIControlStateNormal];
    [withrawalBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    withrawalBtn.titleLabel.font = [UIFont fontS:12];
    [balanceBG addSubview:withrawalBtn];
    [withrawalBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-14);
        make.bottom.offset(-14);
        make.height.mas_equalTo(28);
        make.width.mas_equalTo(106);
        make.top.offset(50);
    }];
    [withrawalBtn addTarget:self action:@selector(toWithdrawal) forControlEvents:UIControlEventTouchUpInside];
    withrawalBtn.hidden = YES;
    _withrawalBtn = withrawalBtn;
    
    QMUILabel *balanL = [BRToolsView br_label:Localized(@"shop_balance") textColor:kColorTitle font:[UIFont fontS:14]];
    [balanceBG addSubview:balanL];
    [balanL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.top.offset(10);
    }];
    
    QMUILabel *balanNumL = [BRToolsView br_label:@"--" textColor:kColorTitle font:[UIFont fontB:17]];
    [balanceBG addSubview:balanNumL];
    [balanNumL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.centerY.equalTo(withrawalBtn.mas_centerY).offset(0);
    }];
    self.balanL = balanNumL;
    
    UIView *line = [BRToolsView getLineView:UIColorMakeWithRGBA(0, 0, 0, 0.12)];
    
    [balanceBG addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-14);
        make.left.offset(14);
        make.top.offset(35.5);
        make.height.mas_equalTo(0.5);
    }];
    
    QMUIButton *wRecordBtn = [[QMUIButton alloc] init];
    wRecordBtn.titleLabel.font = [UIFont br_fontM:12];
    [wRecordBtn setTitleColor:kColorTitle forState:UIControlStateNormal];
    [wRecordBtn setTitle:Localized(@"shop_withdrawalRecord") forState:UIControlStateNormal];
    [wRecordBtn setImage:UIImageMake(@"arrow_right_green6") forState:UIControlStateNormal];
    wRecordBtn.imagePosition = QMUIButtonImagePositionRight;
    wRecordBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [balanceBG addSubview:wRecordBtn];
    [wRecordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-16);
        make.centerY.equalTo(balanL.mas_centerY).offset(0);
    }];
    [wRecordBtn addTarget:self action:@selector(toWRecord) forControlEvents:UIControlEventTouchUpInside];
    wRecordBtn.hidden = YES;
    _wRecordBtn = wRecordBtn;
    
    //--------Overview----
    
    UIStackView *stackTitle = [[UIStackView alloc] init];
    stackTitle.axis = UILayoutConstraintAxisVertical;
    stackTitle.backgroundColor = UIColor.whiteColor;
    stackTitle.layer.cornerRadius = 10;
    stackTitle.layer.masksToBounds = YES;
    [contView addSubview:stackTitle];
    [stackTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.top.equalTo(balanceBG.mas_bottom).offset(50);
        
      
    }];
    _stackTitle = stackTitle;
    
    NSArray *titles2 = @[Localized(@"shop_allProfits"),Localized(@"shop_totalOrders"),Localized(@"shop_payouts")];
    
    for (int i = 0; i < titles2.count; i++) {
        BRODListView *cell = [[BRODListView alloc] init];
       
        [stackTitle addArrangedSubview:cell];
        cell.tag = 2000 + i;
        cell.titleL.text = titles2[i];
        
        if (i == titles2.count - 1) cell.line.hidden = YES;
        
     }
    //--------Merchant Management----
    UIStackView *stack = [[UIStackView alloc] init];
    stack.axis = UILayoutConstraintAxisVertical;
    stack.backgroundColor = UIColor.whiteColor;
    stack.layer.cornerRadius = 10;
    stack.layer.masksToBounds = YES;
    [contView addSubview:stack];
    [stack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.top.equalTo(stackTitle.mas_bottom).offset(50);
        make.bottom.offset(-34);
    }];
    _funcSstack = stack;
    NSArray *titles = @[Localized(@"shop_rentalOrder"),Localized(@"shop_transactionRecord"),Localized(@"shop_myDevice"),Localized(@"shop_setting")];
    NSArray *imgs = @[@"marchant_order",@"marchant_transaction",@"marchant_device",@"marchant_setting"];
    for (int i = 0; i < titles.count; i++) {
        BRImgListView *cell = [[BRImgListView alloc] init];
        cell.titleL.text = titles[i];
        cell.img.image = UIImageMake(imgs[i]);
        [stack addArrangedSubview:cell];
        cell.tag = 600 + i;
        UIControl *tap = [[UIControl alloc] init];
        tap.tag = 500 + i;
        [tap addTarget:self action:@selector(toMenuTag:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:tap];
        [tap mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.offset(0);
        }];
        if (i == titles.count - 1) cell.line.hidden = YES;
     }
    
    // -------------------
    QMUILabel *titleL2 = [BRToolsView br_label:Localized(@"shop_overview") textColor:kColorTitle font:[UIFont fontB:17]];
    [contView addSubview:titleL2];
    [titleL2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(stackTitle.mas_top).offset(-10);
        make.left.offset(20);
    }];
    
    QMUILabel *titleL1 = [BRToolsView br_label:Localized(@"shop_merchantManagement") textColor:kColorTitle font:[UIFont fontB:17]];
    [contView addSubview:titleL1];
    [titleL1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(stack.mas_top).offset(-10);
        make.left.offset(20);
    }];
    
    [self hiddenSetting];
    
    [self.shopListView req_shopList];
    [self.view addSubview:self.shopListView];
    WS(weakSelf);
    self.shopListView.didSelBlock = ^(NSString *brandName) {
        weakSelf.shopListBtn.titleL.text = brandName;
        [weakSelf requestData];
        [weakSelf hiddenSetting];
    };
}

- (BRShopSelView *)shopListView {
    
    if (_shopListView == nil) {
        _shopListView = [[BRShopSelView alloc] init];
        _shopListView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }
    return _shopListView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
